package com.jthinker.blog.service.impl;

import com.jthinker.blog.bean.entity.Post;
import com.jthinker.blog.bean.entity.User;
import com.jthinker.blog.bean.ex.ResourceNotFoundException;
import com.jthinker.blog.bean.vo.PostFilter;
import com.jthinker.blog.bean.vo.QueryResult;
import com.jthinker.blog.dao.BaseDao;
import com.jthinker.blog.dao.PostDao;
import com.jthinker.blog.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * User: Gang Chen
 * Date: 2015/6/27 20:27
 */
@Service
public class PostServiceImpl extends BaseServiceImpl<Post, Long> implements PostService
{
    private PostDao postDao;

    @Autowired
    @Qualifier("postDao")
    @Override
    protected void setBaseDao(BaseDao<Post, Long> baseDao)
    {
        this.baseDao = baseDao;
        this.postDao = (PostDao) baseDao;
    }

    @Cacheable(value = "postList", key = "#filter.toString()")
    @Override
    public QueryResult<Post> queryPagination(PostFilter filter)
    {
        return postDao.queryPagination(filter);
    }

    @Cacheable(value = "recentList", key = "#count")
    @Override
    public List<Post> queryRecentList(int count)
    {
        return postDao.queryRecentList(count);
    }

    @Cacheable(value = "archives")
    @Override
    public List<Object[]> queryArchives()
    {
        return postDao.queryArchives();
    }

    @Cacheable(value = "post", key = "#id")
    @Override
    public Post readDetail(Long id)
    {
        //安全
        Post post = postDao.readDetail(id);

        if (post == null)
        {
            throw new ResourceNotFoundException(String.valueOf(id));
        }
        User user = new User();
        user.setId(post.getUser().getId());
        user.setNickname(post.getUser().getNickname());
        post.setUser(user);
        return post;
    }

    @Caching(evict = { @CacheEvict(value = { "archives", "recentList", "postList" }, allEntries = true), @CacheEvict(value = "post", key = "#id") })
    @Override
    public void delete(Long id)
    {
        super.delete(id);
    }

    @Caching(evict = { @CacheEvict(value = { "archives", "recentList", "postList" }, allEntries = true),
            @CacheEvict(value = "post", key = "#model.id") })
    @Override
    public void merge(Post model)
    {
        super.merge(model);
    }
}
